from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QWidget
from func_timeout import func_set_timeout, FunctionTimedOut
from tufup.client import Client

from src.myapp import settings


class ThreadCheckUpdate(QThread):
    # 声明一个信号
    call_when_boot = False
    init_ui_signal = pyqtSignal()
    update_ui_signal = pyqtSignal(str, str)
    timeout_signal = pyqtSignal()

    def __init__(self):
        super(ThreadCheckUpdate, self).__init__()
        self.w = QWidget()

    def run(self):
        try:
            check_update(self, "")
        except FunctionTimedOut as e:
            print("ThreadCheckUpdate.check_update timed out")
            self.timeout_signal.emit()


@func_set_timeout(3)
def check_update(t, pre):
    print('检查更新')
    new_update = None
    try:
        # Create update client
        client = Client(
            app_name=settings.APP_NAME,
            app_install_dir=settings.INSTALL_DIR,
            current_version=settings.APP_VERSION,
            metadata_dir=settings.METADATA_DIR,
            metadata_base_url=settings.METADATA_BASE_URL,
            target_dir=settings.TARGET_DIR,
            target_base_url=settings.TARGET_BASE_URL,
            refresh_required=False,
        )
        new_update = client.check_for_updates(pre=pre)
    except Exception as e:
        print("检查更新时发生异常")
        print(e)
    if new_update:
        content = new_update.custom["changes"]
        content_str = ""
        if content:
            for item in content:
                content_str += f"- {item}\n"
        print(f"Found new version: {new_update.version}")
        if t.call_when_boot:
            t.init_ui_signal.emit()
        t.update_ui_signal.emit(str(new_update.version), str(content_str))
    # else:
    # checkWindowUi.label_2.setText('您的版本已是最新.')
    # checkWindowUi.label_bbh.setText(f'最新版本:{settings.APP_VERSION} 当前版本: {settings.APP_VERSION}')
